package cn.wolfcode.wms.controllrer;


import cn.wolfcode.wms.domain.Department;
import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.qo.EmployeeOueryObject;
import cn.wolfcode.wms.service.IDepartmentService;
import cn.wolfcode.wms.service.IEmployeeService;
import cn.wolfcode.wms.service.IRoleService;
import cn.wolfcode.wms.util.RequiredPermission;
import cn.wolfcode.wms.vo.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService service;
    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    @RequiredPermission("员工列表")
    public String list(Model model,@ModelAttribute("qo") EmployeeOueryObject qo){
        List<Department> list = departmentService.selectAll();

        PageResult pageResult = service.query(qo);
        model.addAttribute("departments",list);
        model.addAttribute("pageResult",pageResult);
        return "employee/list" ;
    }

    @RequestMapping("/input")
    @RequiredPermission("编辑员工")
    public String input(Model model,Long id){
        model.addAttribute("role",roleService.selectAll());
        List<Department> list = departmentService.selectAll();
            model.addAttribute("departments",list);
        if(id != null){

            model.addAttribute("employee",service.selectByPrimaryKey(id));
        }
        return "employee/input";
    }

    @RequestMapping("/delete")
    @RequiredPermission("员工删除")
    @ResponseBody
    public JSONResult delete(Long id){
        try {
            service.delete(id);
        }catch (Exception e){
            e.printStackTrace();
            JSONResult.mark("删除失败");
        }
        return JSONResult.success("删除成功");
    }

    @RequestMapping("/bacthDelete")
    @RequiredPermission("员工批量删除")
    @ResponseBody
    public JSONResult bacthDelete(@RequestParam("ids[]") Long[] ids){
        try {
            service.deleteIds(ids);
        }catch (Exception e){
            e.printStackTrace();
            JSONResult.mark("删除失败");
        }
        return JSONResult.success("删除成功");
    }



    @RequestMapping("/saveorupdate")
    @RequiredPermission("员工更新或者添加")
    public String saveorupdate(Employee employee ,Long[] ids){

        service.saveorupdate(employee,ids);
        return "redirect:/employee/list.do";

    }
    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return "success";
    }
}
